package com.FengChaoSystem.servlet;


import com.FengChaoSystem.pojo.User;
import com.FengChaoSystem.service.LoginImpl;
import com.FengChaoSystem.service.LoginService.LoginService;
import com.FengChaoSystem.untils.JwtUtil;
import com.FengChaoSystem.untils.SaltMD5Util;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    LoginImpl service=new LoginService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println(username);
        String password = request.getParameter("password");
        System.out.println(password);
        String number = request.getParameter("remember");
        System.out.println(number);

        User user;

        User result = service.selectPasswordByUserName(new User(username, null));
        if(result==null){
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("login.html").forward(request,response);
            return;
        }
        String resultPassWord = result.getPassWord();
        try {
            user = service.login(new User(username,password));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(number);
        if (SaltMD5Util.verifySaltPassword(password, resultPassWord)){
            if ("true".equals(number)) {

                Cookie c_remember = new Cookie("remember",number);
                // 设置Cookie的存活时间

                c_remember.setMaxAge( 60 * 60 * 24 * 7);
                //2. 发送

                response.addCookie(c_remember);
            }
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("username")){
                    username= cookie.getValue();
                    cookie.setMaxAge(0);
                } else if (cookie.getName().equals("password")) {
                    password = cookie.getValue();
                    cookie.setMaxAge(0);
                }
            }


            Cookie c_username = new Cookie("username",username);
            Cookie c_password = new Cookie("password",password);
            // 设置Cookie的存活时间
            c_username.setMaxAge( 60 * 60 * 24 * 7);
            c_password.setMaxAge( 60 * 60 * 24 * 7);
            //2. 发送
            response.addCookie(c_username);
            response.addCookie(c_password);
            //利用session将user数据共享给selectAll请求，因为session能够让两个请求共享数据
            HttpSession session = request.getSession();

            session.setAttribute("phone",result.getPhone());
            session.setAttribute("username",username);
            //获取虚拟路径就可以使其具有多用性
            request.setAttribute("username",username);
            request.setAttribute("identity",result.getIdentity());

            User temp = service.selectIdByUserName(result);
            session.setAttribute("userId",temp.getId());


            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("userId", temp.getId());
            String token = JwtUtil.buildJWT(hashMap);
            session.setAttribute("token",token);
            if(result.getIdentity()==0){
            String ref="http://localhost:8080/ChenXufeng_Fengchao_System/user.html";
            String jsonString = JSON.toJSONString(ref);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);}
            else{
                String ref="http://localhost:8080/ChenXufeng_Fengchao_System/courier.html";
                String jsonString = JSON.toJSONString(ref);
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(jsonString);
            }
        } else {
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("login.html").forward(request,response);

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
